<?php 
/**
 * Класс, который реализовует Extjs Grid
 *
 */

class FRM_View_Ext_CustomGrid extends FRM_View_Ext_Abstract
{
	/**
	 * Enter description here...
	 *
	 * @var int
	 */
	protected $parentField = "id_parent";
	
	/**
	 * Enter description here...
	 *
	 * @var array
	 */
	protected $fields = array();
	
	/**
	 * Enter description here...
	 *
	 * @var string
	 */
	protected $itemTpl;
		
	
	/**
	 * Enter description here...
	 *
	 * @param string $parentField
	 */
	public function setParentField ($parentField){
		$this->parentField = $parentField;
	}
	
	/**
	 * Enter description here...
	 *
	 * @param string $parentField
	 */
	public function setFields ($value){
		$this->fields = $value;
	}
	
	/**
	 * Enter description here...
	 *
	 * @param string $field
	 */
	public function addField ($field){
		$this->fields[] = $field;
	}
	/**
	 * Enter description here...
	 *
	 * @param string $field
	 */
	public function setItemTpl ($itemTpl){
		$this->itemTpl = $itemTpl;
	}
	
	/**
	 * Enter description here...
	 *
	 * @var int
	 */
	protected $baseParams = array();
	
	public function render(){
		
		$this->preRender();
		
		// Reader
		$reader = new PhpExt_Data_JsonReader();
		$reader -> setTotalProperty('totalCount');
		$reader		-> setRoot('data');
		$reader		-> setId('id');
		
		foreach ($this->fields as $field) {
			$name=	(isset($field['name']))?$field['name']:'';
			$map=	(isset($field['map']))?$field['map']:$name;
			$type=	(isset($field['type']))?$field['type']:null;
			if (!empty($name) && isset($field['grid']) && $field['grid']===true)
			{
				$reader->addField(new PhpExt_Data_FieldConfigObject($name,$map));	
			}
		}
		
		$http = new PhpExt_Data_HttpProxy();
		$http -> setUrl($this->url);
		
		$store = new PhpExt_Data_Store();
		$store -> setProxy($http)
			   -> setReader($reader)
			   -> setRemoteSort(true)
			   -> setBaseParams($this->baseParams);
		
		//ToolBar
		$tb = new PhpExt_Toolbar_PagingToolbar();
		$tb -> setPageSize(25)
			-> setStore($store)
			-> setDisplayInfo(true)
			-> setDisplayMessage('Показано {0} - {1} с {2}')
			-> setEmptyMessage('Пусто');
			
		

					
		//Select Model
		$sm = new PhpExt_Grid_RowSelectionModel();
	
		
		//Top ToolBar
		$addHandler = new PhpExt_Handler();
		$addHandler = PhpExt_Javascript::inlineStm("function() {rent.".self::$controller.".currentId=0; Ext.Msg.wait('Подождите...',''); editWindow.show(this);  rvOptions.params.id=0; Ext.Msg.hide();  editForm.form.reset(); 
		if (editForm.form.items.get('hidden_".$this->parentField."'))
		{
			try 
			{
				editForm.form.items.get('hidden_".$this->parentField."').setValue(tree.getSelectionModel().getSelectedNode().attributes.".$this->parentField.");
			}catch (e){}
		}
		}");
		
		$editHandler = new PhpExt_Handler();
		$editHandler = PhpExt_Javascript::inlineStm("function() { var m = dv.getSelectedRecords(); if(m.length == 1){ rent.".self::$controller.".currentId=m[0].get('id'); 
		var galleries = editForm.findByType('dataview'); 
		for (var i=0;i<galleries.length;i++)
		{
			galleries[i].store.baseParams.id=rent.".self::$controller.".currentId;
		}
		rvOptions.params.id=rent.".self::$controller.".currentId; Ext.Msg.wait('Подождите...',''); editWindow.show(); editForm.form.load( { url : '/".self::$module."/".self::$controller."/edit', params : { id : rent.".self::$controller.".currentId} , waitMsg : 'Подождите...'} );} else { Ext.MessageBox.alert('Информация', 'Выберите только один элемент'); }}");

		$removeHandler = new PhpExt_Handler();
		$removeHandler = PhpExt_Javascript::inlineStm("function() {
      var m = dv.getSelectedRecords();
      if(m.length > 0) {
         Ext.MessageBox.confirm('Информация', 'Вы действительно хотите удалить выбранные элементы?', function(btn) {
            if(btn == 'yes') {
               var jsonData = '[{'; for(var i = 0, len = m.length; i < len; i++) {
                  var ss = '\"' + i + '\":\"' + m[i].get('id') + '\"'; if(i == 0) {
                     jsonData = jsonData + ss; }
                  else {
                     jsonData = jsonData + ',' + ss; }
                  store.remove(m[i]); }
               jsonData = jsonData + '}]'; new Ext.data.Store( {
                  autoLoad : true, baseParams : {
                     'delete':jsonData}
                  , failure : function(form, action) {
                     Ext.MessageBox.alert('Ошибка', action.result.msg); }
                  , proxy : new Ext.data.HttpProxy( {
                     url : '/".self::$module."/".self::$controller."/delete'}
                  ), remoteSort : false}
               ); }
            }
         );
         }
      else {
         Ext.MessageBox.alert('Информация', 'Нет вы браных элементов');
         }
      }");
		if (count(self::$langs)){
			
		
		$langCheckHandler = new PhpExt_Handler();
		$langCheckHandler = PhpExt_Javascript::inlineStm("function(item) {
	      defaultLang = item.text;
	      store.baseParams.lang = item.id;
	      store.load( {
	         params : {
	            start : 0,
	         	limit : 25}
	         }
	      );
	      Ext.getCmp('pages-win-lang').setText('Язык: <b>' + defaultLang + '</b>');
	      };");
		
		
		if ($this->currentLang)
		{
			$langs = array();
			foreach (parent::$langs as $k=>$v) {
				$langs[]=array("id"=>$k, "text"=>$v);			
			}
			$langMenu = new PhpExt_Toolbar_MenuButton();
			$langMenu ->setText(PhpExt_Javascript::inlineStm("'Язык: <b>' + defaultLang + ' </b>'"));
			$langMenu ->setMenu(PhpExt_Javascript::inlineStm('{ defaults : { handler : langCheck}, items : '.Zend_Json_Encoder::encode($langs).'}'));
			$langMenu ->setId('pages-win-lang');
		}
		}
		$tbar = new PhpExt_Toolbar_Toolbar();
		$tbar ->addButton("add","Добавить",self::$js."ext/resources/images/default/dd/drop-add.gif",$addHandler);
		$tbar ->addButton("edit","Редактировать",self::$js."ext/resources/images/default/grid/edit.gif",$editHandler);
		$tbar ->addButton("remove","Удалить",self::$js."ext/resources/images/default/grid/remove.gif",$removeHandler);
		if ($this->currentLang && count(self::$langs))
		{
			$tbar ->addItem("lang",$langMenu);
		}
		
		$panel = new PhpExt_Panel();
		$panel->setTitle("Forum Search")
		      ->setHeight(383)	
		      ->setTopToolbar($tbar)
		      ->setBottomToolbar($tb)
 		      ->setHeader(false)
		      ->setAutoScroll(true);
		      
		$dv = new PhpExt_DataView("div.search-item");
		$dv->setStore($store)
		   ->setItemCssSelector("div.search-item")
		   ->setSingleSelect(true)
		   ->setSimpleSelect(true)
		   ->setSelectedCssClass("x-grid3-row-selected")
		   ->setOverCssClass("x-grid3-row-over")
		   ->setTemplate($this->itemTpl);
		$panel->addItem($dv);  
      	
		$stlo = new PhpExt_Data_StoreLoadOptions(array('start'=>0,'limit'=>25));
		     
		PhpExt_Ext::AddOnReady(
			(count(self::$langs))?PhpExt_Javascript::assignNew("defaultLang", "'".parent::$langs[$this->currentLang]."'"):null,
			(count(self::$langs))?PhpExt_Javascript::assignNew("langCheck", $langCheckHandler):null,
			//$colModel->getJavascript(false,'cm'),
			$store->getJavascript(false, "store"),
			$dv->getJavascript(false, "dv"),
			$store->load($stlo),
			$this->itemTpl->getJavascript(false, "resultTpl"),
			$panel->getJavascript(false, "panel"),
			PhpExt_Javascript::inlineStm("function changeImg(msg,records,controller) {
      
      if(records.length > 0) {
       if (msg != '')
       {
         Ext.MessageBox.confirm('Информация', msg, function(btn) {
            if(btn == 'yes') {
                records[0].store.remove(records[0]);
                new Ext.data.Store( {
                  autoLoad : true, baseParams : {
					'id':records[0].get('id')}
                  , failure : function(form, action) {
                     Ext.MessageBox.alert('Ошибка', action.result.msg); }
                  , proxy : new Ext.data.HttpProxy( {
                     url : controller}
                  ), remoteSort : false}
               ); }
            }
         );
	 }else
	 {
	 		records[0].store.remove(records[0]);
                new Ext.data.Store( {
                  autoLoad : true, baseParams : {
                     'id':records[0].get('id')}
                  , failure : function(form, action) {
                     Ext.MessageBox.alert('Ошибка', action.result.msg); }
                  , proxy : new Ext.data.HttpProxy( {
                     url : controller}
                  ), remoteSort : false}
               );
	 }
         }
      else {
         Ext.MessageBox.alert('Информация', 'Нет вы браных элементов');
         }
      }")
			//$grid->getJavascript(false,"grid")
			
		);
	}
}